<template>
  <div class="Resources">
    <div class="page-title">
      <reso-tab v-if="curTab" :tabs="resTabs" :curTab="curTab" @activeIndex="activeIndex" />
    </div>
    <div class="page-head">
      <div class="page-tool between-wrap">
        <div class="between-start">
          <el-select
            v-model="state"
            placeholder="审核状态"
            class="tool-sel"
            clearable
          >
            <el-option
              v-for="item in resStatuses"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            ></el-option>
          </el-select>
          <search-input placeholder="资源名称" @search="searchChange" />
        </div>

        <div class="between-end">
          <!-- <div
            v-if="$permiss(btnPermiss, '标签管理')"
            type="primary"
            class="tool-btn"
            @click="jumpBq"
          >
            标签管理
          </div> -->
          <div
            v-if="$permiss(btnPermiss, '类别管理')"
            type="primary"
            class="tool-btn"
            @click="jump"
          >
            类别管理
          </div>
          <div
            type="primary"
            class="tool-btn"
            @click="open('add')"
            v-if="$permiss(btnPermiss, '新增资源')"
          >
            新增资源
          </div>
        </div>
        
        
      </div>
    </div>
    <div class="page-body">
      <div class="media-list">
        <el-scrollbar class="scroll-bar">
          <el-row>
            <el-col v-for="(item, i) in list" :key="i" :span="6">
              <div class="media-box">
                <div class="media-con">
                  <div class="media-pic res-pic">
                    <img :src="item.cover_url" class="thumb-img" />
                  </div>
                  <div class="media-content res-content">
                    <el-tooltip
                      effect="dark"
                      :content="item.name"
                      placement="left"
                    >
                      <div class="media-name">
                        {{ item.name }}
                      </div>
                    </el-tooltip>
                    <div
                      class="status-content"
                      :class="
                        resStatuses.find((s) => s.key === item.status).className
                      "
                    >
                      {{ resStatuses.find((s) => s.key === item.status).value }}
                    </div>
                  </div>
                  <div class="media-row res-row">
                    <div class="key">上传人</div>
                    <el-tooltip
                      effect="dark"
                      :content="item.user_name"
                      placement="left"
                    >
                      <div class="val">
                        {{ item.user_name }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="media-row res-row">
                    <div class="key">对象</div>
                    <el-tooltip
                      effect="dark"
                      :content="
                        visibilitys.find((v) => v.key === item.visibility).value
                      "
                      placement="left"
                    >
                      <div class="val">
                        {{
                          visibilitys.find((v) => v.key === item.visibility)
                            .value
                        }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="media-row res-row">
                    <div class="key">备注</div>
                    <el-tooltip
                      effect="dark"
                      :content="item.remark"
                      placement="left"
                    >
                      <div class="val">
                        {{ item.remark }}
                      </div>
                    </el-tooltip>
                  </div>
                </div>
                <div class="media-foot res-foot res-media">
                  <div
                    v-if="$permiss(btnPermiss, '绑定')"
                    class="txt-btn spe-btn primary"
                    @click="openSelect(item)"
                  >
                    绑定
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '审核') && item.status == 0"
                    class="txt-btn spe-btn primary"
                    @click="opeExamine(item)"
                  >
                    审核
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '修改')"
                    class="txt-btn spe-btn primary"
                    @click="open('edit', item)"
                  >
                    修改
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '预览')"
                    class="txt-btn spe-btn primary"
                    @click="previewOpen(item)"
                  >
                    预览
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '删除')"
                    class="txt-btn spe-btn error"
                    @click="deleteClicked(item)"
                  >
                    删除
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-scrollbar>
      </div>
    </div>

    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="680px"
      :title="model.type === 'add' ? `新增资源` : `修改资源`"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="100px"
          label-position="left"
        >
          <el-form-item label="名称" class="required">
            <el-input
              placeholder="请输入名称"
              v-model="form.name"
              name="resourceName"
              v-validate="'required|maxLength32'"
            />
            <div
              v-show="errors.has('resourceName')"
              class="el-form-item__error"
            >
              {{ errors.first("resourceName") }}
            </div>
          </el-form-item>
          <el-form-item label="对象" class="required">
            <el-radio-group v-model="form.visibility">
              <el-radio
                v-for="item in visibilitys"
                :key="item.key"
                :label="item.key"
              >
                {{ item.value }}
              </el-radio>
            </el-radio-group>
            <!-- popper-class="block-select" -->
            <el-select
              v-if="form.visibility === 1"
              v-model="form.organizations"
              collapse-tags
              :multiple="true"
              name="organizations"
              v-validate="'required'"
              placeholder="请选择客户"
              class="lenSty"
            >
              <el-option
                v-for="item in orgSel"
                :key="item.org_id"
                :value="item.org_id"
                :label="item.name"
              >
                <el-tooltip effect="dark" placement="bottom">
                  <div slot="content">
                    {{ item.name }}
                  </div>
                  <div>
                    {{ item.name }}
                  </div>
                </el-tooltip>
                   
              </el-option>
            </el-select>
            <div
              v-show="errors.has('organizations')"
              class="el-form-item__error"
            >
              {{ errors.first("organizations") }}
            </div>
          </el-form-item>
          <el-form-item label="文件" class="upload-form-item required">
            <el-tooltip
              v-if="fileName"
              effect="dark"
              placement="bottom"
              :content="fileName"
            >
              <el-input
                :readonly="true"
                v-model="fileName"
                name="fileName"
                v-validate="'required'"
                placeholder="请选择要上传的文件"
              />
            </el-tooltip>
            
            <el-input
              v-else
              :readonly="true"
              v-model="fileName"
              name="fileName"
              v-validate="'required'"
              placeholder="请选择要上传的文件"
            />
            <div v-show="errors.has('fileName')" class="el-form-item__error">
              {{ errors.first("fileName") }}
            </div>
            <input
              type="file"
              class="file-input"
              ref="fileInput"
              @change="fileChange($event)"
            />
            <img src="~assets/img/pick.png" class="pick-img" />
          </el-form-item>
          <el-form-item label="封面" class="required">
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :before-upload="inbeforeUpLoad"
              :http-request="inUploadReq"
              :accept="imgAccept"
            >
              <img
                v-if="form.cover_url"
                key="pic"
                :src="form.cover_url"
                class="upload-img"
              />
              <img
                v-else
                key="default"
                src="~assets/img/upload.png"
                class="upload-img"
              />
            </el-upload>
            <div v-show="fileIconErr" class="el-form-item__error">
              封面不能为空
            </div>
          </el-form-item>
          <el-form-item label="过期自动清除" class="required">
            <el-radio-group v-model="form.clear">
              <el-radio
                v-for="item in autoClears"
                :key="item.key"
                :label="item.key"
              >
                {{ item.value }}
              </el-radio>
            </el-radio-group>
            
            
          </el-form-item>
          

          <el-form-item label="备注">
            <el-input type="textarea" maxlength="128" v-model.trim="form.remark" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="470px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div v-if="[0, 2].includes(deleteStatus)">确定删除资源？</div>
          <div v-else>该资源已经被审核应用，是否确定要删除？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="resourceDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 审核弹窗 -->
    <el-dialog
      :visible.sync="examineVisable"
      width="430px"
      height="100px"
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @click="examineVisable = false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>请选择审核结果</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resourceExamine(2)">不通过</el-button>
        <el-button type="primary" @click="resourceExamine(1)">通过</el-button>
      </span>
    </el-dialog>
    <!-- 预览弹窗 -->
    <div class="resource-dialog" id="previewDialog" v-if="previewVisible">
      <div class="dialog-content">
        <video
          v-if="getFileType(curItem.url) === 'video'"
          :src="curItem.url"
          class="video-native"
          autoplay="autoplay"
          controls="controls"
        >
        </video>
        <div v-if="getFileType(curItem.url) === 'audio'" class="music-wrapper">
          <a-player autoplay :music="music"> </a-player>
        </div>
        <div v-if="getFileType(curItem.url) === 'image'" class="img-wrapper">
          <img :src="curItem.url" />
        </div>
      </div>
      <div class="dialog-button" @click="previewClose">
        <i class="el-icon-close" style="color: #f56c6c"></i>
      </div>
    </div>
    <resources-select
      v-if="selectVisable"
      :apps="apps"
      @cancel="appCancel"
      @sure="appSure"
    />
  </div>
</template>

<script>
import { Loading } from "element-ui";
import APlayer from "vue-aplayer";
import { mapState } from "vuex";
import * as api from "@/api";
import { imgAccept } from "@/consts/consts";
import { resStatuses, visibilitys, autoClears } from "@/consts/codesMap";
import { videoConf, musicConf } from "@/consts/configs";
import { resourcesFormKey } from "@/consts/formKey";
import { md5 } from "@/utils/md5";
import client from "@/utils/oss";
import getFileType from "@/utils/getFileType";
import resoTab from "../../components/libs/resoTab.vue";

export default {
  components: {
    APlayer,
    resoTab,
  },
  data() {
    return {
      btnPermiss: [],
      taglist:[],
      imgAccept,
      list: [],
      state: "",
      search: "",
      resStatuses,
      visibilitys,
      autoClears,
      model: {
        type: "add",
        visible: false,
      },
      getFileType,
      form: {
        ...resourcesFormKey,
      },
      resource_id: "",
      orgSel: [],
      resTabs: [],
      curTab: null,
      curItem: {},
      type_id: "",
      apps: [],
      selectedAppList: [],

      cover_urluploadFile: null,
      carousel_urluploadFile: null,
      push_urluploadFile: null,
      menu_urluploadFile: null,

      visibility: false,
      previewVisible: false,
      selectVisable: false,
      examineVisable: false,
      radio: "3",
      file: {},
      fileName: "",
      fileSize: "",
      deleteStatus: null,
      fileIconErr: false,
      isShowvideoSuf: false,
      loading: null,
      resorceDialog: false,
    };
  },
  computed: {
    ...mapState(["currentResTab"]),

    playerOptions() {
      return videoConf(this.curItem.cover_url, this.curItem.url);
    },

    music() {
      return musicConf(this.curItem.cover_url, this.curItem.url);
    },
  },
  watch: {
    state() {
      this.offset = 0
      this.resourceList();
    },
  },
  methods: {

    open(type, row = null) {
      this.tagList()
      this.$validator.reset();
      this.model.type = type;
      if (row) {
        for (const k in resourcesFormKey) {
          this.form[k] = row[k];
        }
        this.resource_id = row.resource_id;

        const arr = row.url.split("/");
        let fileName = arr[arr.length - 1] 

        this.fileName = decodeURI(fileName) 
      }
      this.model.visible = true;
    },

    close() {
      this.model.visible = false;
      this.form = { ...resourcesFormKey };
      this.fileName = "";
      this.resource_id = "";
      this.fileIconErr = false;
    },
    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          if (!this.form.cover_url) {
            this.fileIconErr = true;
            return;
          }
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
          if (!this.form.cover_url) {
            this.fileIconErr = true;
          }
        }
      });
    },
    searchChange(e) {
      this.offset = 0
      this.search = e;
      this.resourceList();
    },

    fileChange(e) {
      let file = this.$refs.fileInput.files[0];
      console.log('上传图片： ', file)
      this.file = file;
      const { suffix, size } = this.curTab;
      this.fileSize = file.size;
      const sufs = suffix.split(",");
      const arr = file.name.split(".");
      const suf = arr[arr.length - 1].toLowerCase();
      if (!sufs.includes(suf)) {
        return this.$message.warning(`只支持${suffix}文件格式！`);
      }
      if (file.size / 1024 / 1024 > size) {
        return this.$message.warning(`文件大小不能超过${size}M！`);
      }
      this.loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      md5(file).then((res) => {
        this.form.md5 = res;
        let formData = new FormData();
        formData.append("bucket", "resource");
        formData.append("file", file);
        this.upload(file);
      });
      e.target.value = "";
    },
    
    jump() {
      this.$router.push("/category/resType");
    },
    /**标签管理 */
    jumpBq() {
      this.$router.push("/tagManage");
    },
    doSync() {
      this.$notify.closeAll();
      this.$notify({
        title: "成功",
        message: "同步成功",
        type: "success",
      });
    },

    deleteClicked(item) {
      this.deleteStatus = item.status;
      this.resource_id = item.resource_id;
      this.visibility = true;
    },

    previewOpen(item) {
      this.curItem = item;
      // this.resorceDialog= true
      this.previewVisible = true;
    },

    previewClose() {
      this.previewVisible = false;
    },

    openSelect(row) {
      this.resource_id = row.resource_id;
      this.apps = row.apps ?? [];
      this.selectVisable = true;
    },

    opeExamine(row) {
      this.resource_id = row.resource_id;
      this.examineVisable = true;
    },

    activeIndex(item) {
      this.curTab = this.resTabs.find((t) => t.type_id === item.key);
      sessionStorage.setItem('resCurTab', JSON.stringify(this.curTab))
      let suffixData = this.curTab.suffix.split(",");
      let toLowerCasesuffix = suffixData.map((item) => {
        item = item.toLowerCase();
        return item;
      });
      this.curTab.suffix = Array.from(new Set(toLowerCasesuffix)).toString();
      this.type_id = item.key;
      this.resourceList();
    },

    appSure(e) {
      this.selectedAppList = e;
      this.resourceBindApp();
    },
    /**标签下拉 */
    async tagList() {
      const { code, data } = await api.tag(this).tagList({
        offset: 0,
        limit: -1,
      })
      if (code === 0) {
       this.taglist = data
      }
    },
    appCancel() {
      this.selectVisable = false;
    },
    /**通用图片上传前 */
    inbeforeUpLoad(file) {
      console.log('擅长： ', file)
      const typeOk = ['image/png', 'image/PNG', 'image/jpg', 'image/JPG', 'image/jpeg', 'image/JPEG'].includes(file.type)
      if (typeOk) {
        this.uploadFile = file;
        return true;
      } else {
        return this.$message.warning('只支持png、jpg格式的图片')
      }
    },
    /**通用图片上传后 */
    async inUploadReq(){

      let [n, suf] = this.uploadFile.name.split(".");
      let fileName = `${n}_${+new Date()}.${suf}`;
      this.loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.ossPolicy(fileName, this.uploadFile, 'coverUrl')
    },

    
    async ossPolicy(fileName, file, type) {
      const { code, data } = await api.dropdown(this).ossPolicy({
        dir: 'resource'
      });
      if (code === 0) {
        let formData = new FormData()
        formData.append('key', `resource/${fileName}`) // 存储在oss的文件路径
        formData.append('OSSAccessKeyId', data.accessId) // //accessKeyId
        formData.append('policy', data.policy) // policy
        formData.append('Signature', data.signature) //签名
        formData.append('success_action_status', 200)
        formData.append('file', file, fileName)
        this.$axios.post(data.host, formData, {
          headers: { 
            'Content-Type': 'multipart/form-data'
          },
        }).then(res => {
          if (type === 'coverUrl') {
            this.form.cover_url = `${data.host}/resource/${fileName}`
          } else {
            this.form.url = `${data.host}/resource/${fileName}`
            this.fileName = this.file.name
          }
          
          this.loading.close()
        })
      }
    },


    /** */
    async upload(file) {
      let arr = file.name.split(".")
      let [suf, ...rest] = [...arr].reverse()
      let n = rest.reverse().join('.')

      let fileName = `${n}_${+new Date()}.${suf}`;
      // this.ossPolicy(fileName, file, 'url')
      let result = await client.multipartUpload(`resource/${fileName}`, file);
      if (result) {
        [this.form.url] = result.res.requestUrls[0].split("?");
        this.fileName = this.file.name;
        this.loading.close();
      }
    },
    /**Loading */
    openLoading() {
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      })
    },
    // 资源分组
    async resTypeList() {
      const { code, data } = await api.category(this).resTypeList({
        offset: 0,
        limit: -1,
      });
      if (code === 0) {
        this.resTabs = data.map((item) => {
          return {
            ...item,
            key: item.type_id,
            value: item.name,
          };
        });
        let resCurTab = sessionStorage.getItem('resCurTab')
        this.curTab = resCurTab ? JSON.parse(resCurTab) : data[0];
        this.type_id = this.curTab.type_id;
        console.log('当前RES tab: ', this.curTab)
        let suffixData = this.curTab.suffix.split(",");
        let toLowerCasesuffix = suffixData.map((item) => {
          item = item.toLowerCase();
          return item;
        });
        this.curTab.suffix = Array.from(new Set(toLowerCasesuffix)).toString();
        this.resourceList();
      }
    },

    async organizationList() {
      const { code, data } = await api.dropdown(this).organizationList();
      if (code === 0) {
        this.orgSel = data;
      }
    },

    // 资源同步
    async resourceSync() {
      const { code } = await api.resources(this).resourceSync();
      if (code === 0) {
        this.doSync();
      }
    },

    // 资源列表
    async resourceList() {
      const { code, data } = await api.resources(this).resourceList({
        group_id: this.type_id,
        name: this.search,
        state: this.state,
      });
      if (code === 0) {
        this.list = data;
      }
    },
    /**新增编辑接口 */
    async addOrEdit() {
      let fn = this.model.type === "add" ? "resourceAdd" : "resourceUpdate";
      this.form.group_id = this.type_id;
      this.form.size = Math.ceil(this.fileSize / 1024 / 1024).toString();
      this.form.organizations = this.form.organizations || [];

      const { code } = await api.resources(this)[fn](this.form, this.resource_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.resourceList();
      }
    },

    async resourceDelete() {
      const { code } = await api
        .resources(this)
        .resourceDelete(this.resource_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.resource_id = "";
        this.visibility = false;
        this.resourceList();
      }
    },

    async resourceBindApp() {
      const p = {
        apps: this.selectedAppList.map((item) => item.app_id),
      };
      const { code } = await api
        .resources(this)
        .resourceBindApp(p, this.resource_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.selectVisable = false;
        this.resource_id = "";
        this.resourceList();
      }
    },

    async resourceExamine(status) {
      const { code } = await api.resources(this).resourceExamine({
        status,
        resource_id: this.resource_id,
      });
      if (code === 0) {
        this.$message.success("操作成功");
        this.examineVisable = false;
        this.resource_id = "";
        this.resourceList();
      }
    },
  },
  created() {
    this.resTypeList();
    this.organizationList();
    let permission = JSON.parse(localStorage.getItem("permission"))
    let curMenu = permission.find(item => item.txt === "资源管理")
    this.btnPermiss = curMenu.btns
  },
};
</script>

<style lang="stylus">
.Resources {
  #previewDialog {
    .el-dialog__header {
      .el-dialog__headerbtn {
        top: 2px !important;
      }
    }
  }

  .resource-dialog {
    full(fixed);
    overflow: auto;
    margin: 0;
    background: rgba(144, 147, 153, 0.7);
    z-index: 9999;

    .dialog-content {
      width: getPx(950);
      height: getPx(580);
      position: relative;
      margin: 0 auto;
      top: 22%;
    }

    .dialog-button {
      position: absolute;
      // top: 23%;
      // right: 26%;
      top: 18%;
      right: 23%;
      font-size: getPx(24);
      cursor: pointer;
      font-weight: 600 !important;
      z-index: 9999;
    }
  }

  .el-form-item .el-form-item__content .lenSty {
    min-width: 340px;
  }

  .el-select-dropdown__wrap {
    max-width: 344px !important;
  }

  .el-select__tags-text {
    max-width: 308px !important;
  }

  .el-tag.el-tag--info {
    max-width: 245px !important;
  }

  .el-select-dropdown__wrap {
    max-width: 335px !important;
  }

  .page-head {
    padding: 0px !important;
  }

  .el-scrollbar__wrap {
    margin-top: getPx(-3) !important;
  }

  .aplayer-info {
    display: inline-block !important;
    width: 520px !important;
  }

  .aplayer-pic {
    height: 290px !important;
    width: 340px !important;
    margin-top: 25px !important;
  }

  .aplayer .aplayer-body {
    display: flex !important;
    flex-flow: column !important;
    justify-content: flex-start !important;
    align-items: center !important;
  }

  .aplayer .aplayer-body .aplayer-info {
    text-align: center !important;
    padding: 50px 7px 60px 78px !important;
  }
  .aplayer-icon-mode {
    fill:#fff;
  } 
  .img-wrapper {
  width: 100%;
  height: getPx(480) !important;

  img {
    width: 100%;
    height: 100%;
  }
}
  .el-col-4{

  }
}
</style>